package com.zhuhjay.chat.client.handler;

import com.zhuhjay.chat.message.PingMessage;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZhuHJay
 * @date 2023/3/9 12:00
 */
@Slf4j
@ChannelHandler.Sharable
public class HeartbeatTransferHandler extends ChannelDuplexHandler {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent state = (IdleStateEvent) evt;
            // 触发读事件监听
            if (state.state() == IdleState.WRITER_IDLE) {
//                log.info("IdleState.WRITER_IDLE 已经3s没有发送数据");
                // 发送心跳包
                ctx.writeAndFlush(new PingMessage());
            }
        }
    }
}
